﻿using System;

/// <summary>
/// Extension methods
/// </summary>
public static class Extension
{
    /// <summary>
    /// Convert the string to a time value
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static TimeSpan? ToTime(this string value)
    {
        int hours = 0;
        int minutes = 0;
        int seconds = 0;

        if (!string.IsNullOrEmpty(value))
        {
            string[] parts = value.Split(new char[] { ':', '.', ';', ',' });
            if (parts.Length > 0 && parts[0].IsInteger())
            {
                hours = Convert.ToInt32(parts[0]);
                
                if (parts.Length > 1 && parts[1].IsInteger())
                {
                    minutes = Convert.ToInt32(parts[1]);

                    if (parts.Length > 2 && parts[2].IsInteger())
                    {
                        seconds = Convert.ToInt32(parts[2]);
                    }
                }

                return new TimeSpan(hours, minutes, seconds);
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }

    /// <summary>
    /// Return true if the string is an integer (only digits)
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool IsInteger(this string value)
    {
        if (String.IsNullOrEmpty(value))
            return false;

        foreach (char item in value)
        {
            if (!char.IsDigit(item))
                return false;
        }

        return true;
    }

    /// <summary>
    /// Return the time formatted as HH:MM
    /// </summary>
    /// <returns></returns>
    public static string ToHoursMinutes(this TimeSpan? value)
    {
        if (value != null)
            return ToHoursMinutes(value.Value);
        else
            return String.Empty;
    }

    /// <summary>
    /// Return the time formatted as HH:MM
    /// </summary>
    /// <returns></returns>
    public static string ToHoursMinutes(this TimeSpan value)
    {
        return String.Format("{0:00}:{1:00}", (int)value.TotalHours, value.Minutes);
    }
}

